// 定义BTS7960控制引脚
// R_EN和L_EN已直接接3.3V，无需软件控制
const int RPWM = 14;  // 右侧PWM控制引脚
const int LPWM = 27;  // 左侧PWM控制引脚

// 定义PWM参数
const int freq = 5000;      // PWM频率为5kHz
const int pwmChannelR = 0;  // 右侧PWM通道
const int pwmChannelL = 1;  // 左侧PWM通道
const int resolution = 8;   // 8位分辨率，范围0-255

void setup() {
  // 初始化串口通信
  Serial.begin(115200);
  Serial.println("Motor Control Ready!");
  
  // 设置引脚模式
  pinMode(RPWM, OUTPUT);
  pinMode(LPWM, OUTPUT);
  
  // 配置PWM通道
  ledcSetup(pwmChannelR, freq, resolution);
  ledcSetup(pwmChannelL, freq, resolution);
  
  // 将PWM通道绑定到对应引脚
  ledcAttachPin(RPWM, pwmChannelR);
  ledcAttachPin(LPWM, pwmChannelL);
  
  // 初始状态下电机停止
  ledcWrite(pwmChannelR, 0);
  ledcWrite(pwmChannelL, 0);
}

void loop() {
  // 检查串口是否有数据可读
  if (Serial.available() > 0) {
    // 读取串口输入的整数
    int speed = Serial.parseInt();
    
    // 清除串口缓冲区
    while (Serial.available() > 0) {
      Serial.read();
    }
    
    // 控制电机
    controlMotor(speed);
    
    // 打印当前速度
    Serial.print("Speed set to: ");
    Serial.println(speed);
  }
}

void controlMotor(int speed) {
  // 限制速度范围在-255到255之间
  speed = constrain(speed, -255, 255);
  
  if (speed > 0) {
    // 正转
    ledcWrite(pwmChannelR, speed);
    ledcWrite(pwmChannelL, 0);
  } else if (speed < 0) {
    // 反转
    ledcWrite(pwmChannelR, 0);
    ledcWrite(pwmChannelL, abs(speed));
  } else {
    // 停止
    ledcWrite(pwmChannelR, 0);
    ledcWrite(pwmChannelL, 0);
  }
}